//
//  BDRegisterTableViewController.m
//  BeidouMall
//
//  Created by qie on 16/3/31.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDRegisterTableViewController.h"

@interface BDRegisterTableViewController ()
{
    NSTimer *_timer;
    NSInteger _count;
}
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UITextField *verfiyTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwrodTextField;
@property (weak, nonatomic) IBOutlet UITextField *secondpasswrodTextField;

@property (weak, nonatomic) IBOutlet UIButton *getVerifactionButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@end

@implementation BDRegisterTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    self.bottomView.height = kScreen_Height - 204;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark - TextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *futrueString = [textField.text changeCharactersInRange:range replacementString:string];
    
    if ([_userNameTextField.text length]
        && [_accountTextField.text length]
        && [_verfiyTextField.text length]
        && [_passwrodTextField.text length]
        && [_secondpasswrodTextField.text length]) {
        _registerButton.enabled = YES;
    } else {
        _registerButton.enabled = NO;
    }
    
    if (textField.tag == 101) {
        if (futrueString.length > kNickNameLength) {
            futrueString = textField.text;
            return NO;
        }
    } else if (textField.tag == 102) {
        if (futrueString.length > kUserNameLength) {
            return NO;
        }
    } else if (textField.tag == 103) {
        if (futrueString.length > kVerificationMaxLength) {
            return NO;
        }
    } else if (textField.tag == 104) {
        if (futrueString.length > kPasswordMaxLength) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 101) {
        [_accountTextField becomeFirstResponder];
    } else if (textField.tag == 102) {
        [_verfiyTextField becomeFirstResponder];
    }else if (textField.tag == 103) {
        [_passwrodTextField becomeFirstResponder];
    } else if (textField.tag == 104) {
        [_secondpasswrodTextField becomeFirstResponder];
    } else if (textField.tag == 105) {
        [textField resignFirstResponder];
        [self registerButtonPressed:nil];
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == 104) {
        _passwrodTextField.text = nil;
        _secondpasswrodTextField.text = nil;
    } else if (textField.tag == 105) {
        if (_secondpasswrodTextField.text.length > 0) {
            _secondpasswrodTextField.text = nil;
        }
    }
    return YES;
}

#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_userNameTextField.isFirstResponder) {
        [_userNameTextField resignFirstResponder];
    } else if (_accountTextField.isFirstResponder) {
        [_accountTextField resignFirstResponder];
    } else if (_verfiyTextField.isFirstResponder) {
        [_verfiyTextField resignFirstResponder];
    } else if (_passwrodTextField.isFirstResponder) {
        [_passwrodTextField resignFirstResponder];
    }else if (_secondpasswrodTextField.isFirstResponder) {
        [_secondpasswrodTextField resignFirstResponder];
    }
}

#pragma mark - Private method

- (void)updateRequestVerifyCodeButton {
    if (--_count > 0) {
        [_getVerifactionButton setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)_count] forState:UIControlStateDisabled];
    } else {
        _getVerifactionButton.enabled = YES;
        _getVerifactionButton.backgroundColor = kButtonEnableColor;
        NSString *promit = [NSString stringWithFormat:@"%d秒后重发",kWaitTime];
        [_getVerifactionButton setTitle:promit forState:UIControlStateDisabled];
        [_timer invalidate];
    }
}

#pragma mark - IBActions

- (IBAction)getVerificationButtonPressed:(UIButton *)sender {
    if (_accountTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"账号为空"];
    } else if (!([_accountTextField.text isValidPhoneNum] || [_accountTextField.text isVaildEmail])) {
         [MBProgressHUD showToast:self.view withText:@"账号格式不正确"];
    } else {
        
        if (_timer != nil) {
            [_timer invalidate];
        }
        
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,IsRegister];
        [[BDAccountManagerModel shareInstance] checkUserWithUrl:url
                                                          phone:_accountTextField.text
                                                       userType:BUYER
                                              completionHandler:^(NSError *error) {
                                                  if (error != nil) {
                                                      NSLog(@"验证用户:失败%@",[error localizedDescription]);
                                                      NSString *errorStr = [NSString stringWithFormat:@"验证用户失败:%@",[error localizedDescription]];
                                                      [MBProgressHUD showToast:self.view withText:errorStr];
                                                      [_timer invalidate];
                                                      dispatch_async(dispatch_get_main_queue(), ^{// 更新UI操作必须在主线程
                                                          sender.enabled = YES;
                                                          sender.backgroundColor = kButtonEnableColor;
                                                          [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                                                      });
                                                  } else {
                                                      
                                                      NSString *url = [NSString stringWithFormat:@"%@%@?account=%@&type=%@",[BDNetworking shareInstance].baseUrl,VerifyCode,_accountTextField.text,BUYER_REGISTER];
                                                      [[BDAccountManagerModel shareInstance] getVerifyCodeWithUrl:url  completionHandler:^(NSError *error) {
                                                          if (error != nil) {
                                                               NSLog(@"验证码:失败%@",[error localizedDescription]);
                                                              NSString *errorStr = [NSString stringWithFormat:@"获取验证码失败:%@",[error localizedDescription]];
                                                              [MBProgressHUD showToast:self.view withText:errorStr];
                                                              
                                                              [_timer invalidate];
                                                              dispatch_async(dispatch_get_main_queue(), ^{// 更新UI操作必须在主线程
                                                                  sender.enabled = YES;
                                                                  sender.backgroundColor = kButtonEnableColor;
                                                                  [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                                                              });
                                                          } else {
                                                            
                                                          }
                                                      }];
                                                  }
                                              }];
        _count = kWaitTime;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateRequestVerifyCodeButton) userInfo:nil repeats:YES];
        sender.enabled = NO;
        sender.backgroundColor = sender.enabled ? kButtonEnableColor : kButtonDisEnableColor;
    }
    
}

- (IBAction)passwordButtonPressed:(UIButton *)sender {
    sender.selected = !sender.selected;
    _passwrodTextField.secureTextEntry = !sender.selected;
    _secondpasswrodTextField.secureTextEntry = !sender.selected;
}

- (IBAction)secondpwdButtonPressed:(UIButton *)sender {
    sender.selected = !sender.selected;
    _secondpasswrodTextField.secureTextEntry = !sender.selected;
}

- (IBAction)registerButtonPressed:(UIButton *)sender {
    if (_userNameTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"用户名不能为空"];
    } else if (![_userNameTextField.text isValidName]) {
        [MBProgressHUD showToast:self.view withText:@"用户名格式不正确"];
    } else if (_accountTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"账号不能为空"];
    } else if (!([_accountTextField.text isValidPhoneNum] ||
                 [_accountTextField.text isVaildEmail])) {
        [MBProgressHUD showToast:self.view withText:@"账号格式不正确"];
    } else if (_verfiyTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"验证码不能为空"];
    } else if (![_verfiyTextField.text isVaildVerificationCode]) {
        [MBProgressHUD showToast:self.view withText:@"验证码格式不正确"];
    } else if (_passwrodTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"请输入密码"];
    } else if (![_passwrodTextField.text isValidPassword]) {
        [MBProgressHUD showToast:self.view withText:@"密码格式不正确"];
    } else if (_secondpasswrodTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"请输入确认密码"];
    } else if (![_passwrodTextField.text isEqualToString:_secondpasswrodTextField.text]) {
        [MBProgressHUD showToast:self.view withText:@"两次输入的密码不一致"];
    } else {
        if (_userNameTextField.isFirstResponder) {
            [_userNameTextField resignFirstResponder];
        } else if (_accountTextField.isFirstResponder) {
            [_accountTextField resignFirstResponder];
        } else if (_verfiyTextField.isFirstResponder) {
            [_verfiyTextField resignFirstResponder];
        } else if (_passwrodTextField.isFirstResponder) {
            [_passwrodTextField resignFirstResponder];
        } else if (_secondpasswrodTextField.isFirstResponder) {
            [_secondpasswrodTextField resignFirstResponder];
        }
        
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,Register];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@"正在注册"];
        [[BDAccountManagerModel shareInstance] registerWithWithUrl:url
                                                          username:_userNameTextField.text
                                                             phone:_accountTextField.text
                                                          password:_passwrodTextField.text
                                                        verifyCode:_verfiyTextField.text
                                                          userType:BUYER
                                                 completionHandler:^(NSError *error) {
                                                     if (error != nil) {
                                                         NSLog(@"注册失败%@", [error localizedDescription]);
                                                         hud.labelText = [error localizedDescription];
                                                         [hud hideAfterDelay:0.5];
                                                     } else {
                                                         hud.labelText = @"注册成功";
                                                         [hud hideAfterDelay:0.5];
                                                         
                                                         [[BDAccountManagerModel shareInstance] setLogin:YES];
                                                         
                                                         dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
                                                         dispatch_after(time, dispatch_get_main_queue(), ^{
                                                             [self dismissViewControllerAnimated:YES completion:nil];
                                                         });
                                                     }
                                                     
                                                     
                                                 }];
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
